//
//  CSYBlogPictureView.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/15.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let id : String = "pictureViewCell"

private let pictureViewMargin : CGFloat = 5.0000000000000000000000001

class CSYBlogPictureView: UICollectionView {
    
    var imageURLArray : [NSURL]? {
        
        didSet{
            
            reloadData()
            
            let size : CGSize = calculateItemSize()
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.width.equalTo(size.width)
                
                make.height.equalTo(size.height)
                
            }
            
        }
        
    }
    
    //计算Frame
    
    private func calculateItemSize () -> CGSize{
        
        //获取配图的最大宽度
        //列数
        let colum : CGFloat = 3.0000000000000000000000000001
        
        //collectionView的最大宽度
        let maxWidth : CGFloat = screen_Width - 2 * cellMargin
        
        //每张图片的最大宽度
        let itemMaxWidth : CGFloat = (maxWidth - 2 * pictureViewMargin) / colum
        
        //设置Cell的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSizeMake(itemMaxWidth, itemMaxWidth)
        
        
        //计算图片数量:
        let imageCount : NSInteger = imageURLArray?.count ?? 0
        
        if imageCount == 0 {

            
            return CGSizeZero
            
        }
        
        //设置单张图片
        if imageCount == 1 {
            
            //利用SDWebImage框架从默认存储路径(沙盒)中获取图片
            let key = imageURLArray?.last?.absoluteString
            
            print("\(key)")
            
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let imageSize = image.size
            //            let imageSize = CGSize(width: 180, height: 120)
            layout.itemSize = imageSize
            return imageSize
            
            
//            var returnSize : CGSize = CGSizeMake(50, 50)
//
//            let KEY = ((imageURLArray?.last?.absoluteString)! as NSString).appendCachePath()
//            
//            print("ImageURL :: \(imageURLArray?.last)")
//            
//            print("ImageURL :: \(KEY)")
//            
//            let sadboxImage : UIImage? = UIImage(contentsOfFile: (KEY as String))
//            
//            let imageSize = sadboxImage!.size
//            
//            print("正在设置单张图片的宽高值")
//            
//            layout.itemSize = imageSize
//            
//            returnSize = imageSize
//            
//            return returnSize
            
            
            
            
//
//            if sadboxImage == nil {
//
//                print("开始下载缺失图片")
//                
//                let imageData = NSData(contentsOfURL: imageURLArray!.last!)
//                
//                let image : UIImage? = UIImage(data: imageData!)
//                
//                if image != nil {
//                    
//                    let KEY = (imageURLArray!.last!.absoluteString as NSString).appendCachePath()
//                    
//                    imageData?.writeToFile(KEY as String, atomically: false)
//                    
//                    sadboxImage = UIImage(contentsOfFile: (KEY as String))
//                }
//                
//            }
//            
//            let imageSize = sadboxImage!.size
//            
//            print("正在设置单张图片的宽高值")
//            
//            layout.itemSize = imageSize
//            
//            returnSize = imageSize
//            
//            return returnSize
            
        }
        
        //设置四张图片
        if imageCount == 4 {
            
            let width = itemMaxWidth * 2 + pictureViewMargin
            
            return CGSizeMake(width + 1, width)
            
        }
        
        //设置多张图片
        // 1 . 2 . 3 --> row == 1
        
        // 4 . 5 . 6 --> row == 2
        
        // 7 . 8 . 9 --> row == 3
        
        let width : CGFloat = maxWidth
        
        let row = (CGFloat)((imageCount - 1) / 3 + 1)
        
        let height : CGFloat = row * itemMaxWidth + (row - 1) * pictureViewMargin
        
        return CGSizeMake(width, height)
        
    }
    
    //初始化
    
    init() {
        
        let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = pictureViewMargin
        
        layout.minimumLineSpacing = pictureViewMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor.lightGrayColor()
        
        registerClass(CSYBlogPictureViewCell.self, forCellWithReuseIdentifier: id)
        
        self.delegate = self
        
        self.dataSource = self
        
        setUpUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}
    
    //设置UI
    
    private func setUpUI(){
        
        backgroundColor = UIColor(white: 0.96, alpha: 1)
        
    }
    
    //懒加载所有控件
    
    
    
    
}

extension CSYBlogPictureView : UICollectionViewDelegate , UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        print(imageURLArray?.count)
        
        return imageURLArray?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(id, forIndexPath: indexPath) as! CSYBlogPictureViewCell
        
        cell.imageUrl = imageURLArray![indexPath.item]
        
        return cell
        
    }
    
    
}

class CSYBlogPictureViewCell : UICollectionViewCell {
    
    var imageUrl : NSURL? {
        
        didSet{
            
            pictureView.sd_setImageWithURL(imageUrl, placeholderImage: nil)
            
        }
        
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUpUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setUpUI(){
        
        contentView.addSubview(pictureView)
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
            
        }
        
    }
    
    //懒加载所有控件
    lazy var pictureView : UIImageView = {
        
        let view = UIImageView()
        
        view.contentMode = UIViewContentMode.ScaleAspectFill
        
        view.clipsToBounds = true
        
        return view
        
        }()
    
    
}
